PHP - Simple XML GET

    XML has a GET method that will allow you to get the node values from the XML file using the PHP code. Below is some example that will help you to know how data is accessed from XML. Detail.xml file which can be accessed via PHP-

    <DETAIL>
       <COURSE>CS</COURSE>
       <COMPANY>JUST-TIME</COMPANY>
       <PRICE>$10</PRICE>
    </DETAIL>

    Now we will create a file ( index.htm ) that will have the rights to access the above-created XML file data using the simplexml_load_file() method.

    <?php
       $xml = simplexml_load_file("Detail.xml") or die("Error occured");
    ?>
    <html>
       <head>
          <body>
             <?php
                echo $xml->COURSE . "<br>";
                echo $xml->COMPANY . "<br>";
                echo $xml->PRICE;
             ?>
          </body>
       </head>
    </html>

    Below output will be generated-

    CS
    JUST-TIME
    $10

    How to get the node values Below XML file has the data and will allow having information about how the values can be accessed from an XML file ( node_value.xml) .

    <?xml version = "1.0" encoding = "utf-8"?>
    <DATA>   
       <course category = "CS">
          <title lang = "en">Java</title>
          <duration>1</duration>
       </course>
       <course category = "HTML">
          <title lang = "en">Hadoop</title>.
          <duration>3>/duration>
       </course>
    </DATA>

    Below is the PHP code to get the XML node values from the above XML file.

    <html>
       <body>   
          <?php
             $xml = simplexml_load_file("node_value.xml)") or die("Error occured");         
            foreach($xml->children() as $books) { 
                echo $books->title . "<br> "; 
                echo $books->duration . "<br> ";
             }
          ?>      
       </body>
    </html>

    Output

    CS
    Java
    1
    
    HTML
    Hadoop
    3

    People are also reading: